
package com.kilomob.grady.handler.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;

import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kilomob.grady.handler.ChannelHandlerHolder;

/**
 * 
 * connections watchdog.
 * 
 *   
 * @author zhouzhixiang  
 * @date 2017年3月22日
 * @since 1.0
 */
@ChannelHandler.Sharable
public abstract class ConnectionWatchdog extends ChannelInboundHandlerAdapter implements TimerTask, ChannelHandlerHolder {

    private static Logger LOGGER = LoggerFactory.getLogger(ConnectionWatchdog.class);

    private static final int ST_STARTED = 1;
    private static final int ST_STOPPED = 2;
    private static final long RECONNECT_TIMEOUT = 60*1000;

    private final Bootstrap bootstrap;
    private final Timer timer;
    private final SocketAddress remoteAddress;

    private volatile int state;
    private AtomicInteger attempts =  new AtomicInteger(0);
    private long timeout;

    public ConnectionWatchdog(Bootstrap bootstrap, Timer timer, SocketAddress remoteAddress) {
        this.bootstrap = bootstrap;
        this.timer = timer;
        this.remoteAddress = remoteAddress;

        start();
    }

    public boolean isStarted() {
        return state == ST_STARTED;
    }

    public void start() {
        state = ST_STARTED;
    }

    public void stop() {
        state = ST_STOPPED;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel ch = ctx.channel();
        attempts.set(0);
        LOGGER.info("Connects with {}.", ch);
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        boolean doReconnect = isReconnectNeeded();
        if (doReconnect) {
            if(timeout < RECONNECT_TIMEOUT){
//                timeout = 2 << attempts.incrementAndGet();
            }else{
//                timeout = RECONNECT_TIMEOUT;
                attempts.incrementAndGet();
            }
            timer.newTimeout(this, timeout, TimeUnit.MILLISECONDS);
            LOGGER.warn("Disconnects with {}, address: {}, reconnect {}th times with interval {} ms.", ctx.channel(), remoteAddress, attempts.get(),timeout);
        }else{
            LOGGER.warn("Disconnects with {}, address: {} do not reconnect.", ctx.channel(), remoteAddress);
        }

        ctx.fireChannelInactive();
    }

    @Override
    public void run(Timeout timeout) throws Exception {
        if (!isReconnectNeeded()) {
            LOGGER.warn("Cancel reconnecting with {}.", remoteAddress);
            return;
        }

        ChannelFuture future;
        synchronized (bootstrap) {
            bootstrap.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(handlers());
                }
            });
            future = bootstrap.connect(remoteAddress);
        }

        future.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                boolean succeed = f.isSuccess();

                LOGGER.warn("Reconnects with {}, {}.", remoteAddress, succeed ? "succeed" : "failed",f.cause());
                
                if (!succeed) {
                    f.channel().pipeline().fireChannelInactive();
                }
            }
        });
    }

    private boolean isReconnectNeeded() {
        return isStarted();
    }
}
